package com.heer.gymnasium.module.my.views;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RatingBar;

import com.bumptech.glide.Glide;
import com.heer.amap.utils.ToastUtil;
import com.heer.gymnasium.R;
import com.heer.gymnasium.api.ResponseData.ApiResponse;
import com.heer.gymnasium.api.callback.BaseCallback;
import com.heer.gymnasium.base.BaseActivity;
import com.heer.gymnasium.base.BaseRefreshActivity;
import com.heer.gymnasium.module.coach.views.CoachDetailActivity;
import com.heer.gymnasium.module.login.views.LoginActivity;
import com.heer.gymnasium.module.main.views.MainActivity;
import com.heer.gymnasium.module.my.beans.CollectBean;
import com.heer.gymnasium.module.my.beans.CollectCoachBean;
import com.heer.gymnasium.module.my.beans.CollectResponseBean;
import com.heer.gymnasium.module.my.beans.CollectStoreBean;
import com.heer.gymnasium.module.store.views.StoreActivity;
import com.heer.gymnasium.util.DialogUtils;
import com.heer.gymnasium.util.StringUtils;
import com.heer.imagepick.DensityUtils;
import com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayoutDirection;
import com.qict.xinba.Util;
import com.zhihuiyun.library.commonadapter.QuickAdapter;
import com.zhihuiyun.library.commonadapter.QuickInterface;
import com.zhihuiyun.library.commonadapter.QuickTypeAdapter;
import com.zhihuiyun.library.commonadapter.ViewHolder;
import com.zhihuiyun.library.dialog.CommonDialog;
import com.zhihuiyun.library.view.MyGridView;
import com.zhihuiyun.library.view.MyListView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by yan on 2018/1/18.
 * 我的收藏列表
 */

public class MyCollectActivity extends BaseRefreshActivity {
    private static final int LAYOUT_ID = R.layout.layout_collect_list;
    private static final int STORE_RB_ID = R.id.layout_collect_list_store_rb;
    private static final int COACH_RB_ID = R.id.layout_collect_list_coach_rb;
    private static final int STORE_ID = R.id.layout_collect_list_store_ll;
    private static final int COACH_ID = R.id.layout_collect_list_coach_ll;
    private static final int REFRESH_ID = R.id.layout_collect_list_srl;
    private static final int LIST_ID = R.id.layout_collect_list_lv;

    //    item店铺
    private static final int ITEM_LAYOUT_STORE = R.layout.item_store;
    private static final int ITEM_STORE_ICON = R.id.item_store_store_icon_iv;
    private static final int ITEM_STORE_NAME = R.id.item_store_store_name_tv;
    private static final int ITEM_STORE_ICONS = R.id.item_store_icons_ll;
    private static final int ITEM_STORE_ADDRESS = R.id.item_store_store_address_tv;
    private static final int ITEM_STORE_RATINGBAR = R.id.item_store_ratingbar;
    //    item私教
    private static final int ITEM_LAYOUT_COACH = R.layout.item_coach;
    private static final int ITEM_COACH_ICON = R.id.item_coach_icon_iv;
    private static final int ITEM_COACH_NAME = R.id.item_coach_name_tv;
    private static final int ITEM_COACH_RATINGBAR = R.id.item_coach_ratingbar;
    private static final int ITEM_COACH_HOT = R.id.item_coach_hot_tv;
    private static final int ITEM_COACH_TYPES = R.id.item_coach_types_gv;
    //公共的删除图片
    private static final int ITEM_COLLECT_DELETE = R.id.item_collect_delete_tv;
    private static final int ITEM_COLLECT_RIGHT_BOTTOM = R.id.item_collect_right_bottom_ll;

    private List<CollectResponseBean.Item> data;
    private QuickTypeAdapter<CollectResponseBean.Item> adapter;
    @BindView(STORE_RB_ID)
    RadioButton storeRadioButton;
    @BindView(COACH_RB_ID)
    RadioButton coachRadioButton;
    @BindView(LIST_ID)
    ListView listView;

    //    类型1：场馆，2：教练
    private static final int TYPE_STORE = 1;
    private static final int TYPE_COACH = 2;
    private int collectType = TYPE_STORE;
    private boolean canClick = true;//防重复点击

    private MyCollectActivity $this;

    /**
     * TODO 界面跳转，传参需定义
     *
     * @param context
     */
    public static void startActivity(Context context) {
        Intent intent = new Intent(context, MyCollectActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void init() {
        super.init();
        $this = this;
        setContentView(LAYOUT_ID);
        setRefreshResId(REFRESH_ID);
    }

    @Override
    protected void initView() {
        super.initView();
        titleUtils.setTitleText("我的收藏");
        titleUtils.startMainActivity($this);
        data = new ArrayList<>();
        adapter = new QuickTypeAdapter<CollectResponseBean.Item>(this, data) {
            @Override
            public void bindData4View(final ViewHolder holder, final CollectResponseBean.Item data, int type, int pos) {
                //店铺
                if (type == 0) {
                    holder.setText(ITEM_STORE_NAME, data.getStadiumname());
                    holder.setText(ITEM_STORE_ADDRESS, data.getStadiumaddress());
                    Glide.with(context).load(data.getStadiumpic().replace("\\", "/")).into((ImageView) holder.getView(ITEM_STORE_ICON));
                    LinearLayout imagePanel = holder.getView(ITEM_STORE_ICONS);
                    imagePanel.removeAllViews();
                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(DensityUtils.dip2px(context, 15), DensityUtils.dip2px(context, 15));


                    layoutParams.setMargins(0, 0, DensityUtils.dip2px(context, 3), 0);
                    for (int i = 0; i < data.getCategory().size(); i++) {
                        ImageView imageView = new ImageView(context);
                        imageView.setBackgroundResource(R.drawable.black_border);
                        imageView.setPadding(DensityUtils.dip2px(context, 1), DensityUtils.dip2px(context, 1),
                                DensityUtils.dip2px(context, 1), DensityUtils.dip2px(context, 1));
                        Glide.with(context).load(data.getCategory().get(i).replace("\\", "/")).into(imageView);
                        imageView.setLayoutParams(layoutParams);
                        imagePanel.addView(imageView);
                    }
                    //TODO 图标
                    RatingBar bar = holder.getView(ITEM_STORE_RATINGBAR);
                    bar.setRating(5.0f -StringUtils.toFloat(data.getEval_num()));
                    holder.getParentView().setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            StoreActivity.startActivity(context, data.getSid());
                        }
                    });

                    holder.getView(ITEM_COLLECT_DELETE).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            deleteCollectedStore(data.getSid());
                        }
                    });
                }
                //教练
                else {
                    RatingBar bar = holder.getView(ITEM_COACH_RATINGBAR);
                    bar.setRating(5.0f -StringUtils.toFloat(data.getEval_num()));
                    holder.setText(ITEM_COACH_NAME, data.getCoach_name());
                    Glide.with(context).load(data.getAvatar().replace("\\", "/")).into((ImageView) holder.getView(ITEM_COACH_ICON));
                    if (data.getIs_hot().equals("1")) {
                        holder.setVisibility(ITEM_COACH_HOT, View.VISIBLE);
                    } else {
                        holder.setVisibility(ITEM_COACH_HOT, View.GONE);
                    }
                    String[] strArr = data.getCategory_list();
                    MyGridView gridInner = holder.getView(ITEM_COACH_TYPES);
                    gridInner.setNumColumns(3);
                    gridInner.setVerticalSpacing(DensityUtils.dip2px(context, 5));
                    gridInner.setHorizontalSpacing(DensityUtils.dip2px(context, 5));
                    gridInner.setAdapter(new QuickAdapter<String>(context, R.layout.item_tag, strArr) {

                        @Override
                        public void bindData4View(final ViewHolder innerHolder, String data, int pos) {
                            innerHolder.setText(R.id.text, data);
                            innerHolder.getParentView().setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    holder.getParentView().performClick();
                                }
                            });
                        }
                    });

                    holder.getParentView().setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            CoachDetailActivity.startActivity(context, data.getCoach_id());
                        }
                    });

                    holder.getView(ITEM_COLLECT_DELETE).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            deleteCollectedCoach(data.getCoach_id());
                        }
                    });
                }
                holder.setVisibility(ITEM_COLLECT_RIGHT_BOTTOM, View.GONE);
                holder.setVisibility(ITEM_COLLECT_DELETE, View.VISIBLE);

            }
        };
        adapter.addType(0, ITEM_LAYOUT_STORE).addType(1, ITEM_LAYOUT_COACH);
        listView.setAdapter(adapter);
    }

    /**
     * 取消关注教练
     *
     * @param coach_id
     */
    private void deleteCollectedCoach(final String coach_id) {
        if (canClick) {
            canClick = false;
            DialogUtils.showDialog($this, "", "确认取消关注", "", "", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (v.getId() == CommonDialog.RES_ID_POSITIVE) {
                        mAppHelper.apiService().doFocus(FOCUS_TYPE_COACH, coach_id).enqueue(new BaseCallback<ApiResponse<String>>() {
                            @Override
                            public void onSuccess(Call<ApiResponse<String>> call, Response<ApiResponse<String>> response) {
                                canClick = true;
                                ToastUtil.show($this, response.body().getMsg());
                                loadData();
                            }

                            @Override
                            public void onTokenTimeOut() {
                                canClick = true;
                                LoginActivity.logout($this, LoginActivity.TIME_OUT);
                            }

                            @Override
                            public void onError(Call<ApiResponse<String>> call, Throwable t) {
                                canClick = true;
                            }
                        });
                    } else {
                        canClick = true;
                    }
                    DialogUtils.dismissDialog();
                }
            });

        }
    }

    /**
     * 取消关注店铺
     *
     * @param sid
     */
    private void deleteCollectedStore(final String sid) {
        if (canClick) {
            canClick = false;
            DialogUtils.showDialog($this, "", "确认取消关注", "", "", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (v.getId() == CommonDialog.RES_ID_POSITIVE) {
                        mAppHelper.apiService().doFocus(FOCUS_TYPE_STORE, sid).enqueue(new BaseCallback<ApiResponse<String>>() {
                            @Override
                            public void onSuccess(Call<ApiResponse<String>> call, Response<ApiResponse<String>> response) {
                                canClick = true;
                                ToastUtil.show($this, response.body().getMsg());
                                loadData();
                            }

                            @Override
                            public void onFailure(Call<ApiResponse<String>> call, Throwable t) {
                                super.onFailure(call, t);
                                canClick = true;
                            }
                        });
                    } else {
                        canClick = true;
                    }

                    DialogUtils.dismissDialog();
                }
            });

        }
    }

    @Override
    protected void loadData(boolean loadMore) {
        super.loadData(loadMore);
        if (layoutRefresh.isRefreshing()) {
            layoutRefresh.setRefreshing(false);
        }
        getCollectList();
    }

    @OnClick({STORE_ID, COACH_ID})
    public void onClick(View view) {
        switch (view.getId()) {
            case STORE_ID:
                storeRadioButton.setChecked(true);
                coachRadioButton.setChecked(false);
                collectType = TYPE_STORE;
                getCollectList();
                break;
            case COACH_ID:
                storeRadioButton.setChecked(false);
                coachRadioButton.setChecked(true);
                collectType = TYPE_COACH;
                getCollectList();
                break;

        }
    }

    //获得店铺收藏
    private void getCollectList() {
        mAppHelper.apiService().getFocusList(collectType + "").enqueue(new BaseCallback<ApiResponse<CollectResponseBean>>() {
            @Override
            public void onSuccess(Call<ApiResponse<CollectResponseBean>> call, Response<ApiResponse<CollectResponseBean>> response) {
                if (pageNo == 1) {
                    data.clear();
                }
                int total = StringUtils.toInt(response.body().getData().getTotal());
                int current = StringUtils.toInt(response.body().getData().getCurrent_page());
                int per_page = StringUtils.toInt(response.body().getData().getPer_page());
                if (total <= current * per_page) {
                    layoutRefresh.setDirection(SwipyRefreshLayoutDirection.TOP);
                }
                List<CollectResponseBean.Item> itemList = response.body().getData().getData();
                for (int i = 0; i < itemList.size(); i++) {
                    CollectResponseBean.Item item = itemList.get(i);
                    if (collectType == TYPE_STORE) {
                        item.setQuickType(0);
                    } else {
                        item.setQuickType(1);
                    }
                    itemList.set(i, item);
                }
                data.addAll(itemList);

                adapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        canClick = true;
    }
}
